import Template from './basics'
import { FORM_ITEM_TEMPLATE, TABLE_ITEM_TEMPLATE, EDIT_OUTER_TEMPLATES, FORM_DATA_TEMPLATE } from './const'

export default class IndexTemplate extends Template {
    constructor() {
        super()
        this.fields = []
    }

    setListApi({ url, method }) {
        return this.setParams({
            listUrl: url,
            listMethod: method
        })
    }

    setDelApi({ url, method }) {
        return this.setParams({
            delUrl: url,
            delMethod: method
        })
    }

    setEditComponent(isUse = true) {
        const params = isUse ? EDIT_OUTER_TEMPLATES.POSSESS : EDIT_OUTER_TEMPLATES.WITHOUT
        return this.setParams(params)
    }

    setFields(fields) {
        this.fields = fields
        return this.setFormAndTable()
    }

    setFormAndTable() {
        let formData = ''
        let formHtml = ''
        let tableHtml = ''
        for (let i = 0; i < this.fields.length; i++) {
            const field = this.fields[i]
            const template = new Template().setParams(field)

            formData += template.render(FORM_DATA_TEMPLATE)
            formHtml += template.render(FORM_ITEM_TEMPLATE)
            tableHtml += template.render(TABLE_ITEM_TEMPLATE)
        }
        return this.setParams({
            formData,
            formHtml,
            tableHtml
        })
    }
}